package com.bq.gulimall.product.service.impl;

import com.bq.common.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bq.common.utils.PageUtils;

import com.bq.gulimall.product.dao.CategoryDao;
import com.bq.gulimall.product.entity.CategoryEntity;
import com.bq.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1、查出所有的分类
//        List<CategoryEntity> entities = baseMapper.selectList(null); // 或者也可以这样写
        List<CategoryEntity> entities = categoryDao.selectList(null);
        // 2、组装成父子的树形结构
//        2.1、找出所有的一级分类(一级分类的特点就是：它的父ID为0)
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
             categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChilderens(menu,entities));
            return  menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        /**
         * 之所以写成上面的是因为 filter 里面的参数只有一个，{} 里面也只有一个语句就把 {} 去掉了return也去掉了，0后面的 ; 也去掉了
         * List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) ->{
         *     return categoryEntity.getParentCid() == 0;
         * }).collect(Collectors.toList());
         */
        return level1Menus;
    }

//    递归查找所有菜单的子菜单
    private List<CategoryEntity> getChilderens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> childeren = all.stream().filter(CategoryEntity -> {
            return CategoryEntity.getParentCid() == root.getCatId();
        }).map(CategoryEntity -> {
            // 1、找到子菜单
            CategoryEntity.setChildren(getChilderens(CategoryEntity, all));
            return CategoryEntity;
        }).sorted((menu1, menu2) -> {
            // 2、菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return childeren;
    }
}